package com.wc.算法提高课.D第四章_高级数据结构.并查集.银河英雄传说;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

/**
 * @Author congge
 * @Date 2024/5/16 1:46
 * @description https://www.acwing.com/problem/content/240/
 */
public class Main {
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int N = 30010;
    static int[] p = new int[N], siz = new int[N], d = new int[N];
    static int n;

    public static void main(String[] args) {
        n = sc.nextInt();
        for (int i = 1; i < N; i++) {
            p[i] = i;
            siz[i] = 1;
        }
        while (n-- > 0) {
            String op = sc.next();
            int a = sc.nextInt(), b = sc.nextInt();
            if (op.equals("M")) {
                int pa = find(a), pb = find(b);
                if (pa != pb) {
                    // root add size
                    d[pa] = siz[pb];
                    // size[a] += size[b]
                    siz[pb] += siz[pa];
                    p[pa] = pb;
                }
            } else {
                // find(x) has changed d[a], d[b], so res = max(0, abs(d[a] - d[b] - 1)
                int pa = find(a), pb = find(b);
                if (pa == pb) out.println(Math.max(0, Math.abs(d[a] - d[b]) - 1));
                else out.println(-1);
            }
        }
        out.flush();
    }

    static int find(int x) {
        if (p[x] != x) {
            int root = find(p[x]);
            // all add d[p[x]], d[p[x]] has changed, than change d[x]
            d[x] += d[p[x]];
            p[x] = root;
        }

        return p[x];
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}
